<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>询价单详情</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" type="text/css" href="../../common/bootstrap/css/bootstrap.css" media="all">
	<link rel="stylesheet" type="text/css" href="../../common/layui/css/layui.css" media="all">
	<link rel="stylesheet" type="text/css" href="../../common/global.css" media="all">
	<link rel="stylesheet" type="text/css" href="../../css/customer_list.css" media="all">
	<link rel="stylesheet" type="text/css" href="../../common/module/formSelects/formSelects-v4.css" media="all">
</head>
<style>
	.layui-table-cell {
		white-space: normal !important; /* 允许多行显示 */
		word-break: break-all;          /* 长单词或 URL 地址换行 */
	}

	tbody tr .layui-table-cell {
		height: auto !important;
	}
	.layui-form-item .layui-input-inline {
		font-size: 14px;
		width: 240px;
		margin-right: 10px;
	}

	.main_content_wrap{
		margin-top: 0px;
	}
	.detail_wrap{
		padding: 0 50px;
	}
	.max_w{
		max-width: 950px;
	}
	.must{
		color: red;
	}
	.name_no_border{
		border: none;
		width: 200px;
		font-size: 14px;
		margin-bottom: 5px;
	}
	.no-border{
		height: 25px;
		line-height: 25px;
		border: none;
		width: 100px;
	}
	.large_no-border{
		height: 25px;
		line-height: 25px;
		border: none;
		width: 285px;

	}
	.layui-form-label {
		padding-left: 0;
		width: 95px;
	}
	.min-price{
		color: #00A65A;
	}
	.font_color{
		color: #666;
	}
	.qulity{
		width: 80px;
		display: inline-block;
		text-align: left;
	}
</style>
<body>
<!-- 添加车辆和司机 -->
<div class="layui-fluid content_box">
	<div class="main_content_wrap">
		<form class="layui-form add_form" lay-filter="addForm" id="addForm" action="">
			<p class="add_title">基础信息</p>
			<input hidden name="id" />
			<div class="layui-form-item">
				<label class="layui-form-label"><span class="must">*</span>询价来源</label>
				<div class="layui-input-inline">
					<select name="bus_from_company_id" lay-verify="required" id="companyList" lay-search>
					</select>
				</div>
				<label class="layui-form-label"><span class="must">*</span>询价单号</label>
				<div class="layui-input-inline">
					<input type="text" name="bus_inquiry_no" class="layui-input" disabled>
				</div>

				<label class="layui-form-label">询价人</label>
				<div class="layui-input-inline">
					<input type="text" name="bus_user_name" class="layui-input">
				</div>
				<label class="layui-form-label">询价人电话</label>
				<div class="layui-input-inline">
					<input type="text" name="bus_user_phone" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label" ><span class="must">*</span>车牌号码</label>
				<div class="layui-input-inline">
					<input type="text" name="vehicle_license_num"  lay-verify="required"  placeholder="请输入车牌号码" class="layui-input">
				</div>
				<label class="layui-form-label"><span class="must">*</span>车架号</label>
				<div class="layui-input-inline">
					<input type="text" name="vehicle_frame_no" required  lay-verify="required" placeholder="请输入车架号(VIN)" autocomplete="off" class="layui-input">
				</div>
				<label class="layui-form-label"><span class="must">*</span>车辆品牌</label>
				<div class="layui-input-inline">
					<input type="text" name="brand_name" required  lay-verify="required" placeholder="请输入车辆品牌" autocomplete="off" class="layui-input">
				</div>
				<label class="layui-form-label"><span class="must">*</span>车型名称</label>
				<div class="layui-input-inline">
					<input type="text" name="car_model" placeholder="请输入车型名称" required  lay-verify="required" class="layui-input">
				</div>
			</div>

			<div class="layui-form-item">
				<label class="layui-form-label">报案号</label>
				<div class="layui-input-inline">
					<input type="text" name="service_no" placeholder="请输入报案号" autocomplete="off" class="layui-input">
				</div>
				<label class="layui-form-label"><span class="must">*</span>截止时间</label>
				<div class="layui-input-inline">
					<input type="text" name="deadline_datetime" id="deadline_datetime" placeholder="yyyy-MM-DD HH" lay-verify="required" autocomplete="off" class="layui-input">
				</div>


				<label class="layui-form-label">询价日期</label>
				<div class="layui-input-inline">
					<input type="text" name="add_datetime"  autocomplete="off" class="layui-input" disabled>
				</div>

				<label class="layui-form-label">业务员</label>
				<div class="layui-input-inline">
					<input type="text" name="add_user_name"  autocomplete="off" class="layui-input" disabled>
				</div>
				<!--<label class="layui-form-label">车系名称</label>
				<div class="layui-input-inline">
					<input type="text" name="car_series" placeholder="请输入车系名称" autocomplete="off" class="layui-input">
				</div>-->


			</div>


			<div class="layui-form-item">
				<label class="layui-form-label"><span class="must">*</span>配件商</label>
				<div class="layui-input-inline" style="width: 585px">
					<select name="bus_to_company_ids" id="subcompany" xm-select="selSubCompany" lay-search lay-verify="required">
					</select>
				</div>

				<label class="layui-form-label">备注</label>
				<div class="layui-input-inline" style="width: 585px">
					<input type="text" name="common" placeholder="请输入备注" class="layui-input">
				</div>
			</div>

			<p class="add_title">零件清单</p>
			<div class="detail_wrap">
				<div class="layui-form-item">
					<button type="button" class="layui-btn" id="addDetail">
						<i class="layui-icon">&#xe654;</i>新增一行
					</button>
				</div>
				<table class="layui-table max_w" id="infoTable" lay-filter="infoTable"></table>
			</div>
			<!-- 按钮 -->
			<div class="layui-form-item text-center">
				<div class="layui-input-block" style="max-width: none">
					<button class="layui-btn site-demo-active" id="back" style="margin-right: 10%;">返回</button>
					<button class="layui-btn btn-red site-demo-active" style="margin-right: 10%" id="quote">形成报价</button>
					<button class="layui-btn site-demo-active" lay-filter="addFormSubmit" style="margin-right: 10%;background-color: #00A65A"  lay-submit>保存</button>
<!--					<button class="layui-btn site-demo-active" id="againInquiry">再次询价</button>-->
				</div>
			</div>
		</form>
	</div>
</div>
<script type="text/html" id="infoTableBar">
	{{# if(d.id != -1){ }}
	<a class="layui-btn" lay-event="del">删除</a>
	{{# } }}
</script>

<script type="text/html" id="eqname">
	{{# if(d.id != -1 && d.eq_name !== '运费和木架'){ }}
	<input type="text" class="layui-input name_no_border" style="width: 250px" name="eq_name"  lay-filter="eq_name" value="{{d.eq_name}}"><br>
	<span class="qulity" style="width: 45px">OE码:</span>
	<input type="text" class="layui-input name_no_border" name="oe_no" lay-filter="oe_no" value="{{d.oe_no}}">
	<span class="qulity" style="width: 45px">备注:</span>
	<input type="text" class="layui-input name_no_border" name="common" value="{{d.common}}">
	{{# }else{ }}
	<div>{{d.eq_name}}</div>
	{{# } }}
</script>

<script type="text/html" id="eqnum">
	{{# if(d.id != -1){ }}
	<input type="number" class="layui-input name_no_border" name="num"  lay-filter="num" value="{{d.num}}"><br>
	{{# }else{ }}
	<div>{{d.num}}</div>
	{{# } }}
</script>

<script type="text/html" id="qulity">
	{{# if(d.id != -1 && d.eq_name !== '运费和木架'){ }}
	<input type="checkbox" name="qulity_service_state"  lay-filter="qulity_state" value="{{d.qulity_service_state}}" lay-skin="primary" {{d.qulity_service_state ? 'checked' : ''}}> 服务站<br>
	<input type="checkbox" name="qulity_org_state"      lay-filter="qulity_state" value="{{d.qulity_org_state}}" lay-skin="primary" {{d.qulity_org_state ? 'checked' : ''}}> 原厂原包件<br>
	<input type="checkbox" name="qulity_matching_state" lay-filter="qulity_state" value="{{d.qulity_matching_state}}" lay-skin="primary" {{d.qulity_matching_state ? 'checked' : ''}}> 配套件<br>
	<input type="checkbox" name="qulity_complete_state" lay-filter="qulity_state" value="{{d.qulity_complete_state}}" lay-skin="primary" {{d.qulity_complete_state ? 'checked' : ''}}> 品牌件<br>
	<input type="checkbox" name="qulity_suitable_state" lay-filter="qulity_state" value="{{d.qulity_suitable_state}}" lay-skin="primary" {{d.qulity_suitable_state ? 'checked' : ''}}> 适用件<br>
	{{# } }}
</script>
<!-- 形成报价表单弹窗 -->
<script type="text/html" id="companyForm">
	<form lay-filter="companyForm" class="layui-form model-form">
		<input name="id" type="hidden"/>
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="must">*</span>配件商</label>
			<div class="layui-input-inline">
				<select name="add_company_id" lay-verify="required" id="companySuppliersList" lay-search>
				</select>
			</div>
		</div>
		<!--<div class="layui-form-item">
			<label class="layui-form-label"><span class="must">*</span>利润率</label>
			<div class="layui-input-inline">
				<input name="profit_rate" id="profit_rate" placeholder="请输入利润率" type="number" class="layui-input"
					   max="100" lay-verify="required" required/>
			</div>
			<div class="layui-form-mid layui-word-aux">%</div>
		</div>-->
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="must">*</span>原厂件利润率</label>
			<div class="layui-input-inline">
				<input name="org_profit_rate" id="org_profit_rate" placeholder="请输入利润率" type="number" class="layui-input"
					   max="100" />
			</div>
			<div class="layui-form-mid layui-word-aux">%</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="must">*</span>配套件利润率</label>
			<div class="layui-input-inline">
				<input name="matching_profit_rate" id="matching_profit_rate" placeholder="请输入利润率" type="number" class="layui-input"
					   max="100"/>
			</div>
			<div class="layui-form-mid layui-word-aux">%</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="must">*</span>品牌件利润率</label>
			<div class="layui-input-inline">
				<input name="complete_profit_rate" id="complete_profit_rate" placeholder="请输入利润率" type="number" class="layui-input"
					   max="100"/>
			</div>
			<div class="layui-form-mid layui-word-aux">%</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label"><span class="must">*</span>适配件利润率</label>
			<div class="layui-input-inline">
				<input name="suitable_profit_rate" id="suitable_profit_rate" placeholder="请输入利润率" type="number" class="layui-input"
					   max="100"/>
			</div>
			<div class="layui-form-mid layui-word-aux">%</div>
		</div>
		<div class="layui-form-item text-center">
			<button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
			<button class="layui-btn" lay-filter="companyFormSubmit" lay-submit>确认</button>
		</div>
	</form>
</script>
<script type="text/javascript" src="../../js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="../../js/jquery.cookie.js"></script>
<script type="text/javascript" src="../../common/layui/layui2.js"></script>
<script type="text/javascript" src="../../js/common.js"></script>
<script type="text/javascript" src="../../js/main.js"></script>
<script type="text/javascript" src="../../jsplug/xm-select.js"></script>
<script>
	var id = GetQueryString('id');
	layui.use(['jquery','form','laydate', 'admin','table','formSelects'], function(){
		var $ = layui.jquery;
		var form = layui.form;
		var table = layui.table;
		var laydate = layui.laydate;
		var formSelects = layui.formSelects;
		var admin = layui.admin;

		var companyList = {};
		var suppliersCompanyList = {};
		var sys_profit_rate = '';
		var addEqState = 0;
		var tableIns
		laydate.render({
			elem: '#deadline_datetime'
			,trigger: 'click',
			type: 'datetime', // 设置类型为 datetime
			format: 'yyyy-MM-dd HH', // 设置显示格式
		});
		form.render();

		var detail_data = [];
		var detailList = [];
		var scrollPosition = {
			table: 0, // 表格容器的滚动位置
			parent: 0 // 父容器的滚动位置（如果适用）
		};
		var cols = [
			{type: 'numbers', title: '序号'},
			{field: 'eq_name', title: '零件名称',templet:'#eqname',width: 280},
			{field: 'num', title: '数量',templet:'#eqnum',width: 100},
			{field: 'qulity', title: '品质', templet:'#qulity',width: 150},
	];
        var DISABLED = 'layui-btn-disabled';

		send_req('Common/basedata', {}, function (data) {
			companyList = data.company_list;
			suppliersCompanyList = data.suppliers_company_list;
			sys_profit_rate = data.profit_rate;
			setSel();
			getInfo();
			getPriceInfo();
		});

		function getInfo() {
			send_req('Inquiry/getQutationInfo', {id: id}, function (data) {
				detail_data = data;
				form.val('addForm',detail_data);
				if(detail_data.bus_to_company_ids){
					var subcompanys = new Array();
					for (var i = 0; i < detail_data.bus_to_company_ids.length; i++) {
						subcompanys.push(detail_data.bus_to_company_ids[i]);
					}
					formSelects.value('selSubCompany', subcompanys);  // 回显多选框
				}
				form.render();
				form.val('addForm', detail_data);
				form.render();
			});
		}
		function getPriceInfo(){
			send_req('Inquiry/getPriceInfo', {id:id}, function (data) {
				detailList = data.detail_info;
				detailList = detailList.concat(data.all_info)
				/**/
				cols = buildCols(detailList);
				tableIns = table.render({
					elem: '#infoTable',
					data: detailList, // 使用本地数据源
					page: false, // 如果不需要分页，设置为false
					limit:100,
					cols: cols, // 动态生成的列定义
					done: function (res, curr, count) {
						var tableContainer = document.querySelector('#infoTable').parentElement;
						tableContainer.scrollTop = scrollPosition.table;
						// 如果有父容器，也恢复父容器的滚动位置
						if (scrollPosition.parent !== undefined) {
							document.documentElement.scrollTop = scrollPosition.parent || document.body.scrollTop;
						}
					}
				});
			});
		}
        function setSel() {
            var companyStr='<option value="">全部企业</option>';
            for(var i=0;i<companyList.length;i++){
                companyStr+='<option value="'+companyList[i].id+'">'+companyList[i].company_name+'</option>';
            }
            $('#companyList').html(companyStr);

			var subCompanyStr = new Array();
			for (var i = 0; i < suppliersCompanyList.length; i++) {
				subCompanyStr.push({name: suppliersCompanyList[i].suppliers_company_name, value: suppliersCompanyList[i].id});
			}
			formSelects.data('selSubCompany', 'local', {arr: subCompanyStr});
            form.render();
        }
		form.render();

		// 获取表格的列
		function buildCols(data) {
			// 假设所有行都有相同的键（即字段名）
			var suppliers = data[0].suppliers;
			// 构建列定义
			for(var i=0;i<suppliers.length;i++){
				var colDef = {
					field: suppliers[i].add_company_id,
					title: detail_data.state != 1?suppliers[i].suppliers_company_name:suppliers[i].suppliers_company_name + '<a class="layui-btn-a" style="background:none;margin-left:5px" title="退回">\n' +
							'\t\t\t\t<img src="../../img/returnicon.png" class="return" data-suppliers-id="'+suppliers[i].add_company_id+'" style="width: 20px;"/>\n' +
							'\t\t\t</a>',
					templet: getStatusTemplate(i,data)
				}
				cols.push(colDef)
			}
			cols.push({align: 'left', toolbar: '#infoTableBar', title: '操作', width: 80});
			return [cols]; // 注意返回的是二维数组，因为Layui的cols参数是二维数组
		}

		// 配件商报价信息
		function getStatusTemplate(index,data) {
			/*return function(d) {
				if(d.id != -1){
					return '<div><input type="number" class="layui-input no-border" name="qulity_service_price" value="' + d['suppliers'][index].qulity_service_price + '" data-index="'+index+'">服务站</div>' +
						'\t<div><input type="number" class="layui-input no-border" name="qulity_org_price"  value="' + d['suppliers'][index].qulity_org_price + '" data-index="'+index+'">原厂原包件</div>' +
						'\t<div><input type="number" class="layui-input no-border" name="qulity_matching_price"  value="' + d['suppliers'][index].qulity_matching_price + '" data-index="'+index+'">配套件</div>' +
						'\t<div><input type="number" class="layui-input no-border" name="qulity_complete_price"  value="' + d['suppliers'][index].qulity_complete_price + '" data-index="'+index+'">品牌件</div>' +
						'\t<div><input type="number" class="layui-input no-border" name="qulity_suitable_price"  value="' + d['suppliers'][index].qulity_suitable_price + '" data-index="'+index+'">适用件</div>'
				}else{
					return '<div>服务站：'+d['suppliers'][index].qulity_service_price+'</div>' +
							 '\t<div>原厂原包件：'+d['suppliers'][index].qulity_org_price+'</div>' +
							 '\t<div>配套件：'+d['suppliers'][index].qulity_matching_price+'</div>' +
							 '\t<div>品牌件：'+d['suppliers'][index].qulity_complete_price+'</div>' +
							 '\t<div>适用件：'+d['suppliers'][index].qulity_suitable_price+'</div>'
				}
			}*/
			return function(d) {
				if (d.id != -1) {
					return buildPriceHTML(d, index);
				} else {
					return buildDisplayHTML(d, index);
				}
			};
		}

		function buildPriceHTML(d, index) {
			const prices = getPrices(d.suppliers);
			const currentPrices = [
				d.suppliers[index].state>2?d.suppliers[index].qulity_service_price:0,
				d.suppliers[index].state>2?d.suppliers[index].qulity_org_price:0,
				d.suppliers[index].state>2?d.suppliers[index].qulity_matching_price:0,
				d.suppliers[index].state>2?d.suppliers[index].qulity_complete_price:0,
				d.suppliers[index].state>2?d.suppliers[index].qulity_suitable_price:0
			];
				return `
        <div class="">OE码 <input type="text" class="layui-input large_no-border" style="width: 245px;" name="oe_no" value="${d.suppliers[index].oe_no}" data-index="${index}" autocomplete="off"></div>
        <div class="${isMinPrice(currentPrices[0], prices.qulity_service_price) ? 'min-price' : ''}">
        	<input type="text" class="layui-input no-border price" name="qulity_service_price" value="${currentPrices[0]}" data-index="${index}"><span class="qulity">服务站</span>
<!--        	<input type="text" class="layui-input no-border font_color" name="qulity_service_common" value="${d.suppliers[index].qulity_service_common?d.suppliers[index].qulity_service_common:''}" data-index="${index}" autocomplete="off">-->
        </div>
        <div class="${isMinPrice(currentPrices[1], prices.qulity_org_price) ? 'min-price' : ''}">
			<input type="text" class="layui-input no-border price" name="qulity_org_price" value="${currentPrices[1]}" data-index="${index}"><span class="qulity">原厂原包件</span>
<!--			<input type="text" class="layui-input no-border font_color" name="qulity_org_common" value="${d.suppliers[index].qulity_org_common?d.suppliers[index].qulity_org_common:''}" data-index="${index}" autocomplete="off">-->
        </div>
        <div class="${isMinPrice(currentPrices[2], prices.qulity_matching_price) ? 'min-price' : ''}">
        	<input type="text" class="layui-input no-border price" name="qulity_matching_price" value="${currentPrices[2]}" data-index="${index}"><span class="qulity">配套件</span>
        	 <input type="text" class="layui-input no-border font_color" name="qulity_matching_common" value="${d.suppliers[index].qulity_matching_common?d.suppliers[index].qulity_matching_common:''}" data-index="${index}" autocomplete="off">
        </div>
        <div class="${isMinPrice(currentPrices[3], prices.qulity_complete_price) ? 'min-price' : ''}">
			<input type="text" class="layui-input no-border price" name="qulity_complete_price" value="${currentPrices[3]}" data-index="${index}"><span class="qulity">品牌件</span>
			<input type="text" class="layui-input no-border font_color" name="qulity_complete_common" value="${d.suppliers[index].qulity_complete_common?d.suppliers[index].qulity_complete_common:''}" data-index="${index}" autocomplete="off">
        </div>
        <div class="${isMinPrice(currentPrices[4], prices.qulity_suitable_price) ? 'min-price' : ''}">
        	<input type="text" class="layui-input no-border price" name="qulity_suitable_price" value="${currentPrices[4]}" data-index="${index}"><span class="qulity">适用件</span>
        	<input type="text" class="layui-input no-border font_color" name="qulity_suitable_common" value="${d.suppliers[index].qulity_suitable_common?d.suppliers[index].qulity_suitable_common:''}" data-index="${index}" autocomplete="off">
        </div>
        <div class=""><input type="text" class="layui-input large_no-border font_color" name="common" value="${d.suppliers[index].common?d.suppliers[index].common:''}" data-index="${index}" autocomplete="off"></div>
    `;
		}

// 辅助函数：构建显示HTML并应用样式
		function buildDisplayHTML(d, index) {
			const prices = getPrices(d.suppliers);
			const currentPrices = [
				d.suppliers[index].qulity_service_price,
				d.suppliers[index].qulity_org_price,
				d.suppliers[index].qulity_matching_price,
				d.suppliers[index].qulity_complete_price,
				d.suppliers[index].qulity_suitable_price
			];

			return `
        <div class="${isMinPrice(currentPrices[0], prices.qulity_service_price) ? 'min-price' : ''}">服务站：<span>${currentPrices[0]}</span></div>
        <div class="${isMinPrice(currentPrices[1], prices.qulity_org_price) ? 'min-price' : ''}">原厂原包件：<span>${currentPrices[1]}</span></div>
        <div class="${isMinPrice(currentPrices[2], prices.qulity_matching_price) ? 'min-price' : ''}">配套件：<span>${currentPrices[2]}</span></div>
        <div class="${isMinPrice(currentPrices[3], prices.qulity_complete_price) ? 'min-price' : ''}">品牌件：<span>${currentPrices[3]}</span></div>
        <div class="${isMinPrice(currentPrices[4], prices.qulity_suitable_price) ? 'min-price' : ''}">适用件：<span>${currentPrices[4]}</span></div>
    `;
		}

// 获取所有配件商的指定品质的价格最小值
		function getPrices(suppliers) {
			let minPrices = {
				qulity_service_price: Infinity,
				qulity_org_price: Infinity,
				qulity_matching_price: Infinity,
				qulity_complete_price: Infinity,
				qulity_suitable_price: Infinity
			};

			suppliers.forEach(supplier => {
				if (supplier.qulity_service_price > 0 && supplier.state>2)
					minPrices.qulity_service_price = Math.min(minPrices.qulity_service_price, supplier.qulity_service_price);

				if (supplier.qulity_org_price > 0 && supplier.state>2)
					minPrices.qulity_org_price = Math.min(minPrices.qulity_org_price, supplier.qulity_org_price);

				if (supplier.qulity_matching_price > 0 && supplier.state>2)
					minPrices.qulity_matching_price = Math.min(minPrices.qulity_matching_price, supplier.qulity_matching_price);

				if (supplier.qulity_complete_price > 0 && supplier.state>2)
					minPrices.qulity_complete_price = Math.min(minPrices.qulity_complete_price, supplier.qulity_complete_price);

				if (supplier.qulity_suitable_price > 0 && supplier.state>2)
					minPrices.qulity_suitable_price = Math.min(minPrices.qulity_suitable_price, supplier.qulity_suitable_price);
			});

			// Ensure that prices are not left as Infinity if no valid price was found
			for (let key in minPrices) {
				if (minPrices[key] === Infinity) {
					minPrices[key] = null;
				}
			}

			return minPrices;
		}

		// 检查当前价格是否是最小价格
		function isMinPrice(currentPrice, minPrice) {
			return currentPrice == minPrice;
		}
		// 新增一行
		$('#addDetail').click(function (){
			addEqState = 1;
			var suppliers = detailList[0].suppliers;
			var coladd_data = [];
			// 构建列定义
			for(var i=0;i<suppliers.length;i++){
				var coladd = {
					id:0,
					oe_no:'',
					add_company_id:suppliers[i].add_company_id,
					suppliers_company_name:suppliers[i].suppliers_company_name,
					qulity_service_price: 0,
					qulity_org_price: 0,
					qulity_matching_price: 0,
					qulity_complete_price: 0,
					qulity_suitable_price: 0,
					qulity_service_common: '',
					qulity_org_common: '',
					qulity_matching_common: '',
					qulity_complete_common: '',
					qulity_suitable_common: '',
					common: '',
				}
				coladd_data.push(coladd)
			}
			var newData =
				{
					'id':0,
					'eq_name':'',
					'oe_no':'',
					'num':1,
					'common':'',
					'qulity_service_state':0,
					'qulity_org_state':0,
					'qulity_matching_state':0,
					'qulity_complete_state':0,
					'qulity_suitable_state':0,
					'suppliers':coladd_data
				};
			table.cache['infoTable'].splice(-1, 0, newData)
			table.cache['infoTable'][table.cache['infoTable'].length-1].num += 1;
			// 更新表格数据
			reloadTable();
		});

		// 删除一行
		table.on('tool(infoTable)', function (obj) {
			var data = obj.data;
			if (obj.event === 'del') { // 删除
				var tr = obj.tr; // 当前行的 DOM 元素
				// 方法1: 使用 tr 获取行索引
				var rowIndex = tr.index(); // 这是相对于表格中所有行的索引

				// 计算 零件数量
				var delNum = table.cache['infoTable'][rowIndex].num;
				table.cache['infoTable'][table.cache['infoTable'].length-1].num -=  delNum;
				// 计算配件商报价总价
				var suppliers = table.cache['infoTable'][rowIndex].suppliers;

				for(var i=0;i<suppliers.length;i++){
					table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][i].qulity_service_price -= suppliers[i].qulity_service_price
					table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][i].qulity_org_price -= suppliers[i].qulity_org_price
					table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][i].qulity_matching_price -= suppliers[i].qulity_matching_price
					table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][i].qulity_complete_price -= suppliers[i].qulity_complete_price
					table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][i].qulity_suitable_price -= suppliers[i].qulity_suitable_price
				}

				obj.del()
				table.cache['infoTable'].splice(rowIndex,1);
				reloadTable();
			}
		});
		document.getElementById('addForm').addEventListener('click', function(event) {
			if (event.target.tagName.toLowerCase() === 'img' && event.target.classList.contains('return')){
				var suppliers_id = event.target.getAttribute('data-suppliers-id') // 配件商列
				var data_info = {
					id:id,
					bus_to_company_id:suppliers_id
				}
				layer.load(); //上传loading
				send_req('Inquiry/returnSuppliersQuote',data_info,function (res) {
					layer.closeAll('loading');
					layer.msg('提交成功', {icon: 1, time:1500}, function () {
						location.replace('./detail.html?id=' + id);
					});
				},false)
				return false;
			}
		});

		$(document).on('focus', '.price', function() {
			if ($(this).val() == 0) {
				$(this).val(''); // 如果值是'0'，则将其清空
			}
			form.render();
		}).on('blur', '.price', function() {
			var num = Number($(this).val());
			if (isNaN(num) || num <= 0) {
				$(this).val(0); // 如果值是'0'，则将其清空
			}
			form.render();
		});

		document.getElementById('addForm').addEventListener('change', function(event) {
			// 确保我们只监听 input 元素
			if (event.target.tagName.toLowerCase() === 'input' && event.target.classList.contains('layui-input')) {
				// 获取输入框的新值
				var newValue = event.target.value;
				var tag_name = event.target.name;
				var suppliers_index = event.target.getAttribute('data-index') // 配件商列
				var tr = event.target.closest('tr'); // 获取最近的 tr 祖先元素
				if(tr){
					// 如果需要获取当前行的数据，可以这样做：
					var index = tr.getAttribute('data-index'); // 零件行
					var tag_type = ['qulity_service_price','qulity_org_price','qulity_matching_price','qulity_complete_price','qulity_suitable_price'];
					var tag_common_type = ['qulity_service_common','qulity_org_common','qulity_matching_common','qulity_complete_common','qulity_suitable_common'];
					if(tag_type.includes(tag_name)){ //修改价格
						if(isNaN(parseFloat(newValue))){
							newValue = 0;
						}
						var oldValue = table.cache['infoTable'][index]['suppliers'][suppliers_index][tag_name] // 修改之前的值
						table.cache['infoTable'][index]['suppliers'][suppliers_index][tag_name] = newValue;

						if(newValue > 0 && (table.cache['infoTable'][index]['suppliers'][suppliers_index].state <3 || table.cache['infoTable'][index]['suppliers'][suppliers_index].state === undefined)){
							table.cache['infoTable'][index]['suppliers'][suppliers_index].state = 3;
							oldValue = 0;
						}
						oldValue = oldValue?oldValue:0
						var diff = parseFloat(newValue) - parseFloat(oldValue)
						var oldTotal = parseFloat(table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][suppliers_index][tag_name]);
						table.cache['infoTable'][table.cache['infoTable'].length-1]['suppliers'][suppliers_index][tag_name] = parseFloat(oldTotal + diff).toFixed(2)
					}else if(tag_name === 'eq_name'){
						table.cache['infoTable'][index]['eq_name'] = newValue;
					}else if(tag_name === 'oe_no'){
						if(suppliers_index === null){
							table.cache['infoTable'][index]['oe_no'] = newValue;
						}else{
							table.cache['infoTable'][index]['suppliers'][suppliers_index]['oe_no'] = newValue;
						}
					}else if(tag_name === 'common'){
						if(suppliers_index === null){
							table.cache['infoTable'][index]['common'] = newValue;
						}else{
							table.cache['infoTable'][index]['suppliers'][suppliers_index]['common'] = newValue;
						}
					}else if(tag_name === 'num'){
						if(isNaN(parseFloat(newValue))){
							newValue = 1;
						}
						var oldValue = table.cache['infoTable'][index].num // 修改之前的值
						if(!/^\+?[1-9]\d*$/.test(newValue)){
							layer.msg('请输入正整数！');
							// 重新设置回原来的值
							table.cache['infoTable'][index].num = oldValue;
							table.reload('infoTable',{data: table.cache['infoTable']});
							return false;
						}
						var diff = parseInt(newValue) - parseInt(oldValue)
						table.cache['infoTable'][index]['num'] = newValue;
						var oldTotal = parseInt(table.cache['infoTable'][table.cache['infoTable'].length-1]['num']);
						table.cache['infoTable'][table.cache['infoTable'].length-1]['num'] = parseInt(oldTotal + diff)
					}else if(tag_common_type.includes(tag_name)){
						table.cache['infoTable'][index]['suppliers'][suppliers_index][tag_name] = newValue;
					}
					form.render(); // 更新渲染
					reloadTable()
				}
			}
		});

		function reloadTable() {
			var tableContainer = document.querySelector('#infoTable').parentElement;
			scrollPosition.table = tableContainer.scrollTop; // 保存表格容器的滚动位置

			// 如果有父容器，保存父容器的滚动位置
			scrollPosition.parent = document.documentElement.scrollTop || document.body.scrollTop;
			// 表格重载
			tableIns.reload({
				data: table.cache['infoTable'] // 将新数据与现有缓存合并
			});
		}

		form.on('checkbox(qulity_state)', function(data){
			var elem = data.elem; // 获得 checkbox 原始 DOM 对象
			var checked = elem.checked; // 获得 checkbox 选中状态
			var tag_name = elem.name; // 获取id
			// 更新表格
			var tr = elem.closest('tr'); // 使用 jQuery 的 closest 方法，确保你已引入 jQuery
			// 获取当前行的索引
			var index = Array.prototype.indexOf.call(tr.parentNode.children, tr);
			table.cache['infoTable'][index][tag_name] = checked?1:0;
			reloadTable()
			form.render(); // 更新渲染
		});
		// 格式化时间为 YYYY-MM-DD HH:mm:ss
		function formatDate(date) {
			var year = date.getFullYear();
			var month = ('0' + (date.getMonth() + 1)).slice(-2);
			var day = ('0' + date.getDate()).slice(-2);
			var hours = ('0' + date.getHours()).slice(-2);
			return year + '-' + month + '-' + day + ' ' + hours;
		}

		//监听提交----保存
		form.on('submit(addFormSubmit)', function(d){
			var user_info =  JSON.parse(getSessionStorage('uanme'));
			d.field.opt_role_id = user_info.role_id
			d.field.opt_user_id = user_info.user_id;
			d.field.opt_user_name = user_info.true_name;
			d.field.add_state = addEqState;
			var details = layui.table.cache.infoTable;
			details.splice(-1, 1);
			d.field.detail_info = JSON.stringify(details);
			// 增加样式
			$('.site-demo-active').addClass(DISABLED);
			// 增加属性
			$('.site-demo-active').attr('disabled', 'disabled');
			// console.log(d.field)
			layer.load(); //上传loading
			send_req('Inquiry/modifyInquiry',d.field,function (res) {
				layer.closeAll('loading');
				layer.msg('提交成功', {icon: 1, time:1500}, function () {
					location.replace('./detail.html?id=' + id);
				});
			},false)
			return false;
		});

		// 形成报价
		$('#quote').click(function () {
			admin.open({
				type: 1,
				area: '600px',
				offset: '65px',
				title: '形成报价',
				content: $('#companyForm').html(),
				success: function (layero, index) {
					$(layero).children('.layui-layer-content').css('overflow', 'visible');
					var companyStr='<option value="">全部企业</option>';
					for(var i=0;i<detail_data['suppliers'].length;i++){
						companyStr+='<option value="'+detail_data['suppliers'][i].id+'">'+detail_data['suppliers'][i].suppliers_company_name+'</option>';
					}
					$('#companySuppliersList').html(companyStr);
					if(detail_data.sale_price_state >= 1){
						form.val('companyForm',detail_data.from_quotation_selection_json);
					}/*else{
						$("#profit_rate").val(sys_profit_rate)
					}*/
					form.render();
				}
			})
			return false;
		});

		$('#againInquiry').click(function () {
			window.parent.go_to_page_general('./html/inquiry/add.html','id=' + id);
			return false;
		});
		$('#back').click(function () {
			window.parent.go_to_page_general('./html/inquiry/index.html');
			return false;
		});
		//监听提交----形成报价
		form.on('submit(companyFormSubmit)', function(d){
			var add_company_id = d.field.add_company_id;
			// var profit_rate = d.field.profit_rate;
			var org_profit_rate = d.field.org_profit_rate;
			var matching_profit_rate = d.field.matching_profit_rate;
			var complete_profit_rate = d.field.complete_profit_rate;
			var suitable_profit_rate = d.field.suitable_profit_rate;
			window.location.href = './quotation.html?id=' + encodeURIComponent(id) +
					'&supplier_id=' + encodeURIComponent(add_company_id) +
					'&org_profit_rate=' + encodeURIComponent(org_profit_rate) +
					'&matching_profit_rate=' + encodeURIComponent(matching_profit_rate) +
					'&complete_profit_rate=' + encodeURIComponent(complete_profit_rate) +
					'&suitable_profit_rate=' + encodeURIComponent(suitable_profit_rate);
					// '&profit_rate=' + encodeURIComponent(profit_rate);
			return false; // 阻止表单默认提交行为
		});
    });
</script>
</body>
</html>